package cc.customer.web.seaAdmin;

import cc.customer.cusDynamic.domain.ExEmpRecevice;
import cc.customer.expCustomer.domain.ExEmp;
import cc.customer.expCustomer.services.ExEmpServices;
import cc.customer.common.annotation.Log;
import cc.customer.common.domain.QueryRequest;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.DateUtil;
import cc.customer.common.utils.FebsUtil;
import cc.customer.common.utils.FileUtils;
import cc.customer.system.dao.SaleTagMapper;
import cc.customer.system.dao.UserMapper;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.UserService;
import cc.customer.utils.AutonCusInfo;
import cc.customer.web.sys.controller.base.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value="/seaExtension")
public class ExtensionController extends BaseController {

   @Autowired
   private UserService userService;

   private Logger logger = LoggerFactory.getLogger(BaseController.class);

   @Autowired
   private ExEmpServices exEmpServices;
   @Autowired
   private UserMapper userMapper;
    @Autowired
   private SaleTagMapper saleTagDao;

   @RequestMapping(value="/index")
   public String loadIndex(){
      return "customer/seaManage/seaExtension/extension_index";
   }

   /**新增客户**/
   @RequestMapping(value = "/loadAdd")
   public String addCustomerDialog(){return "customer/seaManage/seaExtension/seaExtension_add";}

   /**推广客户得资料详情**/
   @RequestMapping(value = "/exEmpDetail")
   public String exEmpDetail(){ return "customer/myCustomer/myCustomerdetail/ext_detail";}


   /**加载所有推广资源列表**/
   @RequestMapping(value = "/list")
   @ResponseBody
   public Map<String,Object> getAllExEmpList(ExEmp exEmp, QueryRequest request){
       MyUser user = this.getCurrentUser();
       List<String> list = user.getAllAuthority();
       exEmp.setcExCreator(user.getUserUuid());
       if (list.contains(Constant.AMDIN_AUTORITY_EXEMP)){
           exEmp.setcExIsAdmin("yes");
       }

       /**跟进部门筛选*/
       String cExCurrentDept = exEmp.getcExCurrentDept();
       if(!StringUtils.isEmpty(cExCurrentDept)){
           List<String> lists = exEmpServices.parseDeptUsers(cExCurrentDept);
           exEmp.setCureentUsers(lists);
       }

       return this.selectByPageNumSize(request,()->this.exEmpServices.getAllExEmp(exEmp,user));
   }

   /**手动增加推广资源信息**/
   @RequestMapping(value = "/saveExEmp")
   @ResponseBody
   @Log("推广资源新增")
   public ResponseBo saveExEmpCutomer(ExEmp exEmp){
       //验证名字
       String name = exEmp.getcExName();
       if (StringUtils.isEmpty(name)){
           exEmp.setcExName("无姓名");
       }
       exEmp.setcExTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
       //验证手机号
       String phone = exEmp.getcExMobile();
       if (!StringUtils.isEmpty(phone)){
            Boolean isphone = FebsUtil.isPhoneNo(phone);
            if (!isphone){
                return ResponseBo.error("输入得手机格式不正确");
            }
       }
       MyUser myUser = this.getCurrentUser();
       String userid = myUser.getUserUuid();
       exEmp.setcExCreator(userid);
       try {
           return this.exEmpServices.addExEmpCustomer(exEmp);
       }catch (Exception e){
            return ResponseBo.error(e.getMessage());
       }
   }
   /**导出推广客户信息**/
   @RequestMapping(value = "/getAllExEmpByids")
   @ResponseBody
   public ResponseBo getAllExEmpByids(String ids){
      try {
         MyUser user = this.getCurrentUser();
         List<ExEmp> list = this.exEmpServices.getAllExEmpByids(ids,user);
         List<ExEmpRecevice> receviceList = new ArrayList<>();

         for(ExEmp exEmp:list){
             ExEmpRecevice exEmpRecevice = new ExEmpRecevice();
             AutonCusInfo.parseExEmp(exEmp,user);
             MyUser myUsersDang = userService.findUserDetailByUuids(exEmp.getcExReceiver());

             if (myUsersDang !=null) {
                 exEmpRecevice.setExReceviceCurent(myUsersDang.getNickname());
                 exEmpRecevice.setExDeptCurent(myUsersDang.getDeptName());
             }
             exEmpRecevice.setExDept(exEmp.getcExDept());
             exEmpRecevice.setExChat(exEmp.getcExWechat());
             exEmpRecevice.setExName(exEmp.getcExName());
             exEmpRecevice.setExPhone(exEmp.getcExMobile());
             exEmpRecevice.setExTime(exEmp.getcExTime());
             exEmpRecevice.setExctime(exEmp.getcExTime());
             exEmpRecevice.setExQq(exEmp.getcExQq());
             exEmpRecevice.setExChanel(exEmp.getcExChanel());
             exEmpRecevice.setExSource(exEmp.getcExSource());
             exEmpRecevice.setExZone(exEmp.getcExzone());
             exEmpRecevice.setExType("推广资源");
             String fentype = "";
             if("1".equals(exEmp.getcExMethod())){
                 fentype = "自动";
             }else if("2".equals(exEmp.getcExMethod())){
                 fentype = "手动";
             }
             exEmpRecevice.setExFenType(fentype);
             exEmpRecevice.setExIntern(exEmp.getcExIntern());
             exEmpRecevice.setExStage(exEmp.getcExStage());
             exEmpRecevice.setExKey(exEmp.getcExKey());
             exEmpRecevice.setExUrl(exEmp.getcExInit());
             String creatname = "";
             MyUser user1 = userMapper.selectUserDetailByUuid(exEmp.getcExCreator());
             if(user1!=null){
                 creatname = user1.getNickname();
             }else{
                 creatname = exEmp.getcExCreator();
             }
             exEmpRecevice.setExCreator(creatname);

             //标签
             ExEmp ee = new ExEmp();
             ee.setcExId(exEmp.getcExId());
             ExEmp exEmpList = exEmpServices.selectByKey(ee);

             if(exEmpList!=null){
                 String labelid = exEmpList.getcExLabel();
                 StringBuffer sb  = new StringBuffer();
                 if(!StringUtils.isEmpty(labelid)){
                     String[] labids = labelid.split(",");
                     for(String id : labids){
                         String tagname = saleTagDao.selectTagNameById(id);
                         sb.append(tagname+",");
                     }
                     String tags = sb.substring(0,sb.lastIndexOf(","));
                     exEmpRecevice.setExLabel(tags);
                 }
             }

             Date cretime =  DateUtil.convert2Date(exEmp.getcExTime(),DateUtil.FULL_DATE_FORMAT);
             Date recetime = DateUtil.convert2Date(exEmp.getcExTime(),DateUtil.FULL_DATE_FORMAT);
             Long time = DateUtil.diffSecond(recetime,cretime);
             exEmpRecevice.setCrtime(time+" 秒");
             receviceList.add(exEmpRecevice);

         }
         return  FileUtils.createExcelByPOIKit("客户资料表", receviceList, ExEmpRecevice.class);
      }catch (Exception e){
         e.printStackTrace();
      }
      return ResponseBo.error("获取客户失败");
   }
   /**删除推广客户**/
   @RequestMapping(value = "/delAllExEmpByids")
   @ResponseBody
   public ResponseBo delAllExEmpByids(String ids){
      try {
         return this.exEmpServices.deleteExEmp(ids);
      }catch (Exception e){
         e.printStackTrace();
      }
      return ResponseBo.error("删除客户失败");
   }
    /**获取推广客户资料**/
    @RequestMapping(value = "/getExEmpDetail")
    @ResponseBody
    public ResponseBo getExEmpDetail(String ids){
        MyUser user = this.getCurrentUser();
        return this.exEmpServices.getExEmpDetail(ids,user);
    }

    /**获取推广客户的标签**/
    @RequestMapping(value = "/getExEmpDetailLabel")
    @ResponseBody
    public ResponseBo getExEmpDetailLabel(String ids){
        return this.exEmpServices.getExEmpDetailLabel(ids);
    }

    /**修改推广客户资料**/
    @RequestMapping(value = "/updateExEmpDetail")
    @ResponseBody
    public ResponseBo updateExEmpDetail(ExEmp exEmp){
        MyUser user = this.getCurrentUser();
        exEmp.setcExRecent(user.getNickname()+Constant.GENZONG_RECORD_ZILAO);
        exEmp.setcExRecentTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        return this.exEmpServices.updateExEmpInfo(exEmp,user);
    }
    /**批量修改推广资源客户的信息**/
    @RequestMapping(value = "/batchUpdateExEmp")
    @ResponseBody
    public ResponseBo batchUpdateExEmp(String ids,ExEmp exEmp){
        MyUser user = this.getCurrentUser();
        exEmp.setcExRecent(user.getNickname()+Constant.GENZONG_RECORD_ZILAO);
        exEmp.setcExRecentTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        exEmp.setcExCreator(user.getUserUuid());
        try {
            return this.exEmpServices.batchUpdateExEmp(ids,exEmp);
        }catch (Exception e){
            return  ResponseBo.error();
        }
    }

    /**同步接收落地页数据*/
    @RequestMapping(value = "/receiveSchoolData")
    @ResponseBody
    public synchronized  ResponseBo receiveData(ExEmp exEmp){
       String name = exEmp.getcExName();
       if (StringUtils.isEmpty(name)){
          exEmp.setcExName("无姓名");
       }
       if(StringUtils.isEmpty(exEmp.getcExMobile())){
          if(StringUtils.isEmpty(exEmp.getcExWechat())){
             if(StringUtils.isEmpty(exEmp.getcExQq())){
                return ResponseBo.error("联系方式为空");
             }
          }
       }
       Boolean ble = exEmpServices.isHaveExEmpByMobileOrQqOrWechat(exEmp.getcExMobile(),exEmp.getcExWechat(),exEmp.getcExQq());
       if (ble){
           logger.error("网站后台数据传输事务，已经存在当天得数据");
           return ResponseBo.error("当天已经存在");
       }

       if(!Constant.BIGEMP_BANLCE_GROUP.contains(exEmp.getcExGroud())){
          return ResponseBo.error("意向等级必须为A,B,C,D中一类");
       }
       if(StringUtils.isAnyEmpty(exEmp.getcExCreator())){
          exEmp.setcExCreator(Constant.RECEIVE_SYS_ID);
       }
//       if(StringUtils.isAnyEmpty(exEmp.getcExInit(),exEmp.getcExIntern(),exEmp.getcExKey(),exEmp.getcExSource(),exEmp.getcExChanel(),
//               exEmp.getcExzone(),exEmp.getcExZiSource(),exEmp.getcExGroud())){
//          return  ResponseBo.error("缺少必填项");
//       }
       exEmp.setcExStatusjin("1");
       exEmp.setcExTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
       exEmp.setcExMethod(Constant.EXEMP_AUTO_DIS);
       logger.info(exEmp.getcExName());
       try {
           return this.exEmpServices.addExEmpCustomer(exEmp);
       }catch (Exception e){
           return ResponseBo.error(e.getMessage());
       }
    }
    /**对接易聊的信息接口**/
    @PostMapping(value = "exEmpRemoteYILIAO")
    @ResponseBody
    public synchronized  ResponseBo  getYiLiaoExEmpInfo(ExEmp exEmp){
        String name = exEmp.getcExName();

        if (StringUtils.isEmpty(name)){ exEmp.setcExName("无姓名"); }
        String zone = exEmp.getcExzone();
        if (StringUtils.isEmpty(zone)){exEmp.setcExzone("未获取");}
        /**意向等级**/
        exEmp.setcExGroud("A");
        String exname= exEmp.getcExCreator();
        String InterName  = paseExIntern(exname);
        exEmp.setcExIntern(InterName); //意向项目
        exEmp.setcExCreator("e0905447f40446f4ba419a5ba7fd3e95"); //创建为常量
        exEmp.setcExStatusjin("1");
        exEmp.setcExTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        exEmp.setcExMethod(Constant.EXEMP_AUTO_DIS);
        if (StringUtils.isEmpty(exEmp.getcExChanel())){
            exEmp.setcExChanel("无数据");
        }
        exEmp.setcExZiSource("易聊名片");
        try {
            return this.exEmpServices.addExEmpCustomer(exEmp);
        }catch (Exception e){
            return ResponseBo.error(e.getMessage());
        }
    }
    private String paseExIntern(String exId){
        String Intern = "";
        switch (exId){
            case "AI-juxue":
            case "AI-juxue01":
            case "juxuezk":
                Intern =  "自学考试";
                break;
            case "AI-juxueck01":
            case "juxueck":
                Intern =  "成考辅导";
                break;
            case "AI-juxuezzy01":
            case "juxuezzy":
                Intern =  "在职研";
                break;
            case "juxuezcb":
                Intern =  "总裁班";
                break;
            case "juxuezksw":
            case "AI-juxuezksw01":
                Intern =  "自考省外";
                break;
            case "juxuelx":
                Intern =  "出国留学";
                break;
            case"juxuejks":
            case"AI-juxuejkgl01":
                Intern =  "健康管理师";
                break;
            case"juxue5gpx":
                Intern =  "5G培训";
                break;
            case"juxuetzzsb":
                Intern =  "普通专升本";
                break;
            case"AI-juxuezkhn01":
            case"juxuezkhn":
                Intern =  "海南自考";
                break;
            default:
        }
        return Intern;
    }


    /**对接广点通信息接口**/
    @PostMapping(value = "exEmpRemoteGUANGDIAN")
    @ResponseBody
    public synchronized ResponseBo exEmpRemoteGUANGDIAN(ExEmp exEmp){
        try {
            String name = exEmp.getcExName();

            if (StringUtils.isEmpty(name)){ exEmp.setcExName("无姓名"); }
            String zone = exEmp.getcExzone();
            if (StringUtils.isEmpty(zone)){exEmp.setcExzone("未获取");}
            /**意向等级*/
            exEmp.setcExGroud("A");
            String exname= exEmp.getcExCreator();
            String InterName  = paseExInGuang(exname);
            exEmp.setcExIntern(InterName); //意向项目
            exEmp.setcEclueCreatid(exEmp.getcExCreator());
            exEmp.setcExCreator("信息流"); //创建为常量
            exEmp.setcExStatusjin("1");
            exEmp.setcExTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
            exEmp.setcExMethod(Constant.EXEMP_AUTO_DIS);
            exEmp.setcExChanel("广点通");
            if (StringUtils.isEmpty(exEmp.getcExChanel())){
                exEmp.setcExChanel("无数据");
            }
            exEmp.setcExZiSource("广点通名片");
            logger.error("广点通名片"+exEmp.toString()+"------------");
            return this.exEmpServices.addExEmpCustomer(exEmp);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResponseBo.error(e.getMessage());
        }
    }


    private String paseExInGuang(String exId){
        String Intern = "";
        switch (exId){
            case "14839676":
                Intern =  "自学考试";
                break;
            case "14573787":
                Intern =  "总裁班";
                break;
            case "14573782":
                Intern =  "出国留学";
                break;
            case "14839698":
                Intern =  "健康管理师";
                break;
            case "14466524":
                Intern =  "健康管理师";
                break;
            case "14386135":
                Intern =  "5G培训";
                break;
            default:
        }
        return Intern;
    }



    /**对接今日头条信息接口**/
    @PostMapping(value = "receiveTouTiao")
    @ResponseBody
    public synchronized ResponseBo receiveTouTiao(ExEmp exEmp){
        try {
            String name = exEmp.getcExName();

            if (StringUtils.isEmpty(name)){ exEmp.setcExName("无姓名"); }
            String zone = exEmp.getcExzone();
            if (StringUtils.isEmpty(zone)){exEmp.setcExzone("未获取");}
            /**意向等级*/
            exEmp.setcExGroud("A");
            String exname= exEmp.getcEclueCreatid();
            String InterName  = paseExInTou(exname);
            exEmp.setcExIntern(InterName); //意向项目

            exEmp.setcExCreator("信息流"); //创建为常量
            exEmp.setcExStatusjin("1");
            exEmp.setcExTime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
            exEmp.setcExMethod(Constant.EXEMP_AUTO_DIS);
            if (StringUtils.isEmpty(exEmp.getcExChanel())){
                exEmp.setcExChanel("无数据");
            }
            logger.error("头条名片"+exEmp.toString()+"------------");
            return this.exEmpServices.addExEmpCustomer(exEmp);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResponseBo.error(e.getMessage());
        }
    }

    private String paseExInTou(String exId){
        String Intern = "";
        switch (exId){
            case "1664544772315143":
                Intern =  "健康管理师";
                break;
            case "1664749107934216":
            case "1668479048541198":
                Intern =  "自学考试";
                break;
            default:
        }
        return Intern;
    }

}